package yc.star.common.security.interceptor;


import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import yc.star.common.constants.Constant;
import yc.star.common.constants.HttpConstants;
import yc.star.common.security.service.TokenService;
import yc.star.common.utils.ThreadLocalUtil;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Value("${jwt.secret}")
    private String secret; // 从哪个配置文件中获取，取决于这个bean交给了哪个spring容器管理

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = getToken(request);
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        // 从token中拿到userId和userKey
        Long userId = tokenService.getUserId(token, secret);
        String userKey = tokenService.getUserKey(token, secret);
        // 将userId存储到ThreadLocal变量中
        ThreadLocalUtil.set(Constant.USER_ID,userId);
        ThreadLocalUtil.set(Constant.USER_KEY,userKey);
        // 判断redis中用户信息的有效时长，如果不足则进行延时
        tokenService.extendToken(token,secret);
        return true;
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}